import axios from "../../axios";
import { useEffect, useState } from "react";
import { AudioOutlined } from '@ant-design/icons';
import { Table, Select,Tabs, Input, Space, Button, Modal, message } from 'antd';
const { Search } = Input;

function UserManage() {

    const [selectedRowKeys, setSelectedRowKeys] = useState([]);//拿到选中的id************************
    const onSelectChange = (newSelectedRowKeys) => {
        // console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    const [list, setList] = useState([])
    const [page, setPage] = useState(1)
    const [userType, setUserType] = useState("")
    const [keywords, setkeywords] = useState("")
    const [total, setTotal] = useState(0)
    const [limit2, setLimit] = useState(15)
    const getlist = async () => {//********************** *请求
        let { list, total, limit } = await axios.get("/user/list", {
            params: {
                keywords,
                userType,
                page,
                labelId: "",
                sex: "",
                isPromoter: "",
                country: "",
                payCount: "",
                accessType: 0,
                dateLimit: "",
                province: "",
                city: "",
                limit: limit2,
                level: "",
                groupId: "",
                temp: new Date().getTime(),
            }
        })
        setList(list)
        setTotal(total)
        setLimit(limit)
    }

    const columns = [//*************************************************表格数据 */
        {
            title: 'ID',
            dataIndex: 'uid',
            key: 'uid',
        },
        {
            title: '头像',
            dataIndex: 'age',
            key: 'age',
            render: (_, react) => <img src={react.avatar} />
        },
        {
            title: '姓名',
            dataIndex: 'nickname',
            key: 'nickname',
        },
        {
            title: 'A用户等级tion',
            dataIndex: 'level',
            key: 'level',

        },
        {
            title: '分组',
            dataIndex: 'groupName',
            key: 'groupName',

        },
        {
            title: '推荐人',
            dataIndex: 'spreadNickname',
            key: 'spreadNickname',

        },
        {
            title: '手机号',
            dataIndex: 'phone',
            key: 'phone',

        },
        {
            title: '余额',
            dataIndex: 'nowMoney',
            key: 'nowMoney',

        },
        {
            title: '积分',
            dataIndex: 'signNum',
            key: 'signNum',

        },
        {
            title: '操作',
            dataIndex: '',
            key: 'x',
            render: (_, row) => {
                return (<div className="fa">
                    <span onClick={editorFun}>编辑</span>
                    <span onClick={()=>detail(row)}>详情</span>
                    <span onClick={()=>singleGroup(row)}>分组</span>
                </div>)
            }

        },
    ];
  const editorFun=()=>{
    message.open({
        type: 'error',
        content: '没有权限',
    });
  }

    const onChange = (key) => {//选项卡单击事件
        console.log(key);
        setUserType(key)
    };
    const items = [//选项卡数据
        {
            key: ' ',
            label: '全部',
        },
        {
            key: 'wechat',
            label: '微信公众号用户',
        },
        {
            key: 'routine',
            label: '微信小程序用户',
        },
        {
            key: 'h5',
            label: 'H5用户',
        },
    ];


    //***************************搜索 */
    const onSearch = (value) => {
        console.log(value)
        setkeywords(value)

    };



    useEffect(() => {
        getlist()
    }, [page, userType, keywords])
    const onChangePage = (a, b) => {
        console.log(a, b);
        setPage(a)
    }


    // 发放优惠券
    const [isModalOpen, setIsModalOpen] = useState(false);
    const handleCancel = () => { setIsModalOpen(false); };
    const [pageQuan, setpageQuan] = useState(1)
    const [keywordsQuan, setkeywordspageQuan] = useState("");
    const [listQuan, setlistQuan] = useState([])
    const getQuan = async () => {
        let { list, total } = await axios.get("/marketing/coupon/send/list", {
            params: {
                page: pageQuan,
                limit: 10,
                keywords: keywordsQuan,
                type: 1,
                temp: new Date().getTime(),
            }
        })
        setlistQuan(list)
    }
    const columnsQuan = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '优惠券名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '优惠券面值',
            dataIndex: 'money',
            key: 'money',
        },
        {
            title: '最低消费额',
            dataIndex: 'minPrice',
            key: 'minPrice',
        },
        {
            title: '有效期',
            dataIndex: 'day',
            key: 'day',
        },
        {
            title: '剩余数量',
            dataIndex: 'lastTotal',
            key: 'lastTotal',
        },
        {
            title: '操作',
            dataIndex: 'x',
            key: 'x',
            render: (_, row) => <Button size="mini" onClick={() => send(row)}>发送</Button>
        },
    ]
    const disPatchFun = () => {// 展示弹出层
        if (selectedRowKeys.length == 0) {
            message.open({
                type: 'error',
                content: '没有可操作的事项',
            });
            return false
        }
        setIsModalOpen(true);
        getQuan() // 请求 得到所有的优惠券
    }
    const send = async (row) => {
        console.log(row.id);
        console.log(selectedRowKeys);

        let res = await axios.post(`/marketing/coupon/user/receive?couponId=${row.id}&uid=${selectedRowKeys.join(",")}`)
        getQuan() // 请求 得到所有的优惠券
        setIsModalOpen(false);
    }

    // 批量设置分组
    const [isModalOpengroup, setIsModalOpengroup] = useState(false);
    const handleCancelgroup = () => { setIsModalOpengroup(false); setdefaultValue("") ;       setNum(0) };
    const getSelect = async () => {
        let { list } = await axios.get("/user/group/list", { params: { page: 1, limit: 9999, temp: new Date().getTime() } })
        setgroupOptions(list)
    }
    const [groupOptions,setgroupOptions]=useState([])
    const handleChange = (value) => {
        setdefaultValue(value)
      };
      const [num,setNum]=useState(0)
    const showGroup = () => {
        setNum(2)
        setIsModalOpengroup(true);
        getSelect()
    }
    const [defaultValue,setdefaultValue]=useState("")

    const yesGroup=()=>{// 确定选择
        
         if(num==2){//多个
            groupAxios(defaultValue,selectedRowKeys)
         }else{//  num==1  单个
            groupAxios(defaultValue,[rowId])
         }
    }
    const  groupAxios=async (groupId,id)=>{// 封装分组
         let res=await axios.post(`/user/group?groupId=${groupId}&id=${id.join(",")}`)

         setIsModalOpengroup(false);
        setdefaultValue("")
        getlist()
    }

// 单个分组
const [rowId,setrowid]=useState("")
const  singleGroup=(row)=>{
    console.log(row);
    
    setIsModalOpengroup(true);
    setNum(1)
    setrowid(row.uid)
    getSelect()
   
}
// 详情事件

const [rowobj,setrowobj]=useState({})
const  detail=(row)=>{
    console.log(row);
    
    setrowobj(row)
}
    return (<div className="whitebg">
        <Tabs defaultActiveKey="1" items={items} onChange={onChange} />
        <Search placeholder="搜索" onSearch={onSearch} enterButton />

        <Button type="primary" onClick={disPatchFun}>发送优惠卷</Button>
        <Modal title="发送优惠券" open={isModalOpen} footer={null} onCancel={handleCancel}>
            <Table dataSource={listQuan} rowKey="id" columns={columnsQuan} />;
        </Modal>


        <Button onClick={showGroup} disabled={selectedRowKeys.length == 0} type="primary" danger>批量设置分组</Button>
        <Modal title="分组" open={isModalOpengroup} footer={null} onCancel={handleCancelgroup}>
        <Select
      value={defaultValue}
      style={{width:"200px"}}
      autoClearSearchValue={true}
      onChange={handleChange}
      options={groupOptions}
      fieldNames={{label:"groupName",value:"id"}}
    />

     <div>
     <Button type="primary" onClick={yesGroup}>确定</Button>
     </div>
        </Modal>
        <Table
            columns={columns}
            rowSelection={rowSelection}
            expandable={{
                expandedRowRender: (record) => (
                    <div>
                        <div>
                            首次访问时间：{record.createTime}
                        </div>
                        <div>
                            手机号：{record.phone}
                        </div>
                        <div>
                            标签：{record.mark}
                        </div>
                        <div>
                            国家：{record.country}
                        </div>
                    </div>
                ),

            }}
            dataSource={list}
            rowKey={"uid"}
            pagination={{
                defaultCurrent: page,
                showQuickJumper: true,
                showPrevNextJumpers: true,

                pageSize: limit2,
                total: total,
                pageSizeOptions: [15, 30, 45, 60, 100],
                onChange: onChangePage
            }}
        />

    </div>);
}

export default UserManage;